import pdb
from datetime import datetime
from pypinyin import pinyin, Style
from sqlalchemy import func

from app.models import db


class Station(db.Model):
    __tablename__: str = 'station'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), unique=True, nullable=False, index=True)
    pinyin = db.Column(db.String(120))
    province = db.Column(db.String(120))
    city = db.Column(db.String(120))
    district = db.Column(db.String(120))
    created_at = db.Column(db.DateTime, default=func.now())
    updated_at = db.Column(db.DateTime, default=func.now())

    def __repr__(self):
        return f'<Station {self.name}>'

    @classmethod
    def create(cls, data):
        station = cls(
            name=data.get('name'),
            pinyin=''.join([item[0] for item in pinyin(data.get('name'), style=Style.NORMAL)]).upper(),
            province=data.get('province'),
            city=data.get('city'),
            created_at=datetime.now(),
            updated_at=datetime.now(),
        )
        db.session.add(station)
        db.session.commit()
        return station

    @classmethod
    def destroy(cls, station_id):
        station = cls.query.get(station_id)
        if station:
            db.session.delete(station)
            db.session.commit()
            return True
        return False
